/* --------------------------------------------------------
 * Copyright (c) aeky , Inc.  All rights reserved.
 * --------------------------------------------------------
 */
package com.aeky.client.view.base;

import com.aeky.client.common.AppParams;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.WindowCloseListener;
import com.smartgwt.client.widgets.layout.Layout;

/**
 * 
 * @author aeky
 */
public class ContentApplication extends Layout {

    private AekyWidget currentContent = null;

    private AekyContentPanel contentPanel;

    public ContentApplication() {
        this.initHead();
        this.initContent();
        this.initEvents();
    }

    protected void initHead() {

    }

    protected void initContent() {
        contentPanel = new AekyContentPanel();
        // contentPanel.setAutoHeight();
        // contentPanel.setShowEdges(Boolean.FALSE);
        // contentPanel.setID("contentPanel");
        // this.addMember(contentPanel);
    }

    public AekyWidget getCurrentContent() {
        return currentContent;
    }

    /**
     * Sets the content.
     * 
     * @param widget the new content
     */
    public void setContent(final AekyWidget widget) {
        contentPanel.removeAll();
        if (widget != null) {
            contentPanel.addMember(widget);
        }
        this.currentContent = widget;
        // contentPanel.draw();
        // this.contentPanel.show();
    }

    /**
     * @return the contentPanel
     */
    public Layout getContentPanel() {
        return contentPanel;
    }

    @SuppressWarnings("deprecation")
    private void initEvents() {
        Window.addWindowCloseListener(new WindowCloseListener() {
            public String onWindowClosing() {
                return "abcd";
            }

            public void onWindowClosed() {
            }
        });
    }

    public void showContent(AekyWidget widget) {
        this.addToHistory(widget);
    }

    private void addToHistory(final AekyWidget widget) {
        if (widget != null) {
            final String token = widget.getToken();
            Command command = new Command() {
                public void execute() {
                    AppParams.getInstance().addWidgetHistory(widget);
                    if ((currentContent != null && currentContent.getToken().equals(widget.getToken()))
                            || widget.getToken().equals(History.getToken())) {
                        setContent(widget);
                    } else {
                        History.newItem(token);
                    }
                }
            };
            command.execute();
        } else if (widget == null) {
            this.setContent(null);
        }
    }
}
